"use strict";
$(function () {
    yams.menu.select('contractManagement');
    yams.page = {
        /**
         * 初始化页面
         */
        init: function () {
            Dolphin.form.parse();
            let queryParam = {
                house_account_obj_ae : yams.context.checkAdmin()
            }
            if ($("#fromFlag").val() != null
                && $("#fromFlag").val() != undefined
                && $("#fromFlag").val() == 'deadlineHouse') {

                const nowStr = Dolphin.date2string(new Date(), "yyyy-MM-dd");
                const date = new Date();
                date.setDate(date.getDate() + 15);
                const afterStr = Dolphin.date2string(date, "yyyy-MM-dd");

                $("#end_startDate").val(nowStr);
                $("#end_endDate").val(afterStr);
                queryParam = {
                    house_account_obj_ae : yams.context.checkAdmin(),
                    endDate_gt : nowStr,
                    endDate_le : afterStr
                }
            }
            this.initDataList(queryParam);
            this.initEvent();
            this.initUserSearch();
            this.initHouseSearch();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;

            //新建合同
            $(".newData").click(function () {
                Dolphin.form.empty('.edit-form');
                Dolphin.ajax({
                    url: '/api/5d76558d7690404e983ad377d1138a5e',
                    type: Dolphin.requestMethod.POST,
                    onSuccess: function (reData) {
                        console.log(reData);
                        $("#contractCode").val(reData.value.code);
                    }
                });
                $("#contractStatus").val('1');
                $("#payStatus").val('0');
                $('#dataModal').modal('show');
            });

            //保存合同
            $(".modelSave").click(function () {
                let ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    if (data.startDate)
                        data.startDate += " 00:00:00";
                    if (data.endDate)
                        data.endDate += " 00:00:00";
                    data['uedit'] = yams.page.um.getContent();
                    Dolphin.ajax({
                        url: '/api/509cb2a903d2466b9645432e025609c4',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {

                            //生成合同生成第一次账单
                            Dolphin.ajax({
                                url: '/api/abadf0c9542b4ba2aaacc819055d7d9c',
                                type: Dolphin.requestMethod.PUT,
                                data: Dolphin.json2string({"id" : reData.value.id }),
                                onSuccess: function (reData) {
                                    me._dataList.load();
                                    $('#dataModal').modal('hide');
                                }
                            });

                        }
                    });

                }
            });

            $("#billType").change(function () {
                $(".bill-edit-form").find('.aa').addClass('hidden');
                $(".bill-edit-form").find('.a' + $(this).val()).removeClass('hidden');
            });

            $(".billSave").click(function () {
                let ef = $(".bill-edit-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    Dolphin.ajax({
                        url: '/api/4bd717c1cca5449a8a82c1b1584f87d3',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            $('#billDataModal').modal('hide');
                        }
                    });

                }
            });

            //打印
            $(".printContract").click(function (){
                $('.printContent').printThis();
            });


            $(".btn-query").click(function () {
                me._dataList.load(null, Dolphin.form.getValue('.query-form'))
            });
        },

        initDataList: function (queryParam) {
            let me = this;
            me._dataList = new Dolphin.LIST({
                panel: "#dataList",
                title: '合同列表',
                idField: 'id',
                queryParams: queryParam,
                columns: [{
                    code: 'userName',
                    title: '会员名称',
                    width: '110px'
                }, {
                    code: 'houseName',
                    title: '房屋名称',
                    formatter:function (val,row) {
                        return val+''+row.house.houseNumber;
                    }
                }, {
                    code: 'code',
                    title: '合同编码',
                    width: '150px'
                }, {
                    code: 'rental',
                    title: '月租金',
                    width: '100px',
                    textAlign: 'right'
                }, {
                    code: 'startDate',
                    title: '合同日期',
                    width: '200px',
                    formatter: function (val, row) {

                        return (row.startDate?row.startDate.substr(0, 10):'') + '~' + (row.endDate?row.endDate.substr(0, 10):'');
                    }
                }, {
                    code: 'statusName',
                    title: '合同状态',
                    width: '90px'
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '250px',
                    formatter: function (val, row, index) {
                        let html = [];
                        if (row.status == 1) {
                            html.push(yams.buttons.edit({
                                id: row.id
                            }));
                        }
                        html.push('<a class="btn btn-outline btn-circle btn-sm yellow billBtn" ' +
                            'data-id="' + val + '" href="javascript:;"><i class="fa fa-envelope-open"></i>生成账单</a>');
                        html.push('<a class="btn btn-outline btn-circle btn-sm green printBtn" ' +
                            'data-id="' + val + '" href="javascript:;"><i class="fa fa-envelope-open"></i>合同</a>')
                        return html.join('');
                    }
                }],
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/509cb2a903d2466b9645432e025609c4',
                pagination: true,
                onLoadSuccess: function () {
                    yams.buttons.editCallback('ae5b4154f12b4ad5a074eaefec3b47bb', 'id', function (data) {
                        if (data && data.value && data.value['uedit'])
                            yams.page.um.setContent(data.value['uedit']);
                        $("#startDateInput").val(data.value.startDate.substr(0,10));
                        $("#endDateInput").val(data.value.endDate.substr(0,10));
                        $('#dataModal').modal('show');
                    });

                    $('.billBtn').click(function () {
                        let _this = $(this);
                        Dolphin.ajax({
                            url: '/api/ae5b4154f12b4ad5a074eaefec3b47bb@id=' + _this.data('id'),
                            type: Dolphin.requestMethod.GET,
                            onSuccess: function (reData) {
                                if (reData && reData.value) {
                                    let billData = {
                                        contract: {id: reData.value.id},
                                        preWater: reData.value.water,
                                        preElectric: reData.value.electric,
                                        preGas: reData.value.gas,
                                        rentalAmount: reData.value.rental,
                                        pledgeAmount: reData.value.payStatus === 1 ? 0 : reData.value.pledge,
                                        type: ''
                                    };
                                    $("#lastWater").html(billData.preWater);
                                    $("#lastElectric").html(billData.preElectric);
                                    $("#lastGas").html(billData.preGas);
                                    Dolphin.form.setValue(billData, '.bill-edit-form');
                                    $('#billDataModal').modal('show');
                                }
                            }
                        });
                    });

                    $('.printBtn').click(function () {
                        let _this = $(this);
                        Dolphin.ajax({
                            url: '/api/ae5b4154f12b4ad5a074eaefec3b47bb@id=' + _this.data('id'),
                            type: Dolphin.requestMethod.GET,
                            onSuccess: function (reData) {
                                let end=reData.value.endDate.split("-");
                                let start=reData.value.startDate.split("-");
                                let totalFee=(reData.value.house.propertyFee)*(reData.value.house.area)*(parseInt(end[1])-parseInt(start[1]))+reData.value.tvFee+reData.value.otherFee+reData.value.pledge+reData.value.rental;
                                if (reData && reData.value) {
                                    let printData = {
                                        userName : reData.value.user.name,
                                        idCard : reData.value.user.idCard,
                                        houseAddress : reData.value.house.address,
                                        payCycle:reData.value.payCycle,
                                        houseArea : reData.value.house.area,
                                        startDateYear : reData.value.startDate.substr(0,4),
                                        startDateMonth : reData.value.startDate.substr(5,2),
                                        startDateDay : reData.value.startDate.substr(8,2),
                                        endDateYear : reData.value.endDate.substr(0,4),
                                        endDateMonth : reData.value.endDate.substr(5,2),
                                        endDateDay : reData.value.endDate.substr(8,2),
                                        a1:totalFee,
                                        a2:Dolphin.numToCny(parseInt(totalFee/1000)).substring(0,1),
                                        a3:Dolphin.numToCny(parseInt(totalFee/100%10)).substring(0,1),
                                        a4:Dolphin.numToCny(parseInt(totalFee/10%10)).substring(0,1),
                                        a5:Dolphin.numToCny(parseInt(totalFee%10)).substring(0,1),
                                        otherPlan:reData.value.otherPlan,
                                        b2:reData.value.house.propertyFee,
                                        b1:reData.value.tvFee,
                                        b3:reData.value.otherFee,
                                        tenancy : Dolphin.getMonthNumber(reData.value.startDate, reData.value.endDate),
                                        pledge : reData.value.pledge,
                                        pledgeCny : Dolphin.numToCny(reData.value.pledge),
                                        rental : reData.value.rental,
                                        rentalCny : Dolphin.numToCny(reData.value.rental),
                                        type : ''
                                    };
                                    Dolphin.form.setValue(printData, '.print-edit-form');

                                    if(reData.value.house.products && reData.value.house.products.length > 0){
                                        $("#houseProducts").append("<ul>");
                                        $.each(reData.value.house.products,function(i,obj){
                                            $("#houseProducts").append("<li>"+obj.name+"</li>");
                                        });
                                        $("#houseProducts").append("</ul>");
                                    }

                                    $('#printModal').modal('show');
                                }
                            }
                        });
                    });
                }
            });
        },

        /**
         * 会员搜索
         */
        initUserSearch: function () {
            let me = this;
            $("#customerId").bsSuggest({
                delayUntilKeyup: true,
                allowNoKeyword: false,   //是否允许无关键字时请求数据。为 false 则无输入时不执行过滤请求
                multiWord: false,         //以分隔符号分割的多关键字支持
                separator: ",",          //多关键字支持时的分隔符，默认为空格
                getDataMethod: "url",    //获取数据的方式，总是从 URL 获取
                effectiveFields: ["name", "phone", "idCard", "status"],
                effectiveFieldsAlias: {name: '姓名', phone: "手机", idCard: "证件号", status: "状态"},
                idField: 'id',
                keyField: 'code',
                url: (yams.context.contextPath == '/' ? '' : yams.context.contextPath) + '/api/8f7def63cc5845468b2c65a69abb0664', //优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数
                listStyle: {
                    'padding-top': 0,
                    'max-height': '425px',
                    'max-width': '800px',
                    'overflow': 'auto',
                    'border': '1px solid',
                    'width': 'auto',
                    'transition': '0.3s',
                    '-webkit-transition': '0.3s',
                    '-moz-transition': '0.3s',
                    '-o-transition': '0.3s'
                },                              //列表的样式控制
                listAlign: 'left',              //提示列表对齐位置，left/right/auto
                listHoverStyle: 'background: #07d; color:#000', //提示框列表鼠标悬浮的样式
                fnAdjustAjaxParam: function (keyword, opt) {
                    let data = {memo1: keyword};
                    return {
                        type: 'POST',
                        data: data,
                        dataType: 'json',
                        beforeSend: function (XMLHttpRequest) {
                            let requestHeaderParam = Dolphin.defaults.ajax.requestHeader;
                            for (let key in requestHeaderParam) {
                                XMLHttpRequest.setRequestHeader(key, requestHeaderParam[key]);
                            }
                        }
                    };
                },
                fnPreprocessKeyword: function (kw) {
                    if (kw.length < 3)
                        return false;
                    return kw;
                },
                fnProcessData: function (json) {    // url 获取数据时，对数据的处理，作为 fnGetData 的回调函数
                    let index, len, data = {value: []};
                    data.value = json.rows;
                    //字符串转化为 js 对象
                    return data;
                }
            }).on('onDataRequestSuccess', function (e, result) {
                if (result.total == 0) {
                    alert("该用户未通过实名认证");
                    $("#userId").val('');
                    $("#customerName").val('');
                }
            }).on('onSetSelectValue', function (e, keyword, data) {
                $("#userId").val(data.id);
                $("#customerName").val(data.name);
            }).on('onUnsetSelectValue', function () {
            });
        },

        /**
         * 房间搜索
         */
        initHouseSearch: function () {
            let me = this;
            $("#houseCode").bsSuggest({
                delayUntilKeyup: true,
                allowNoKeyword: false,   //是否允许无关键字时请求数据。为 false 则无输入时不执行过滤请求
                multiWord: false,         //以分隔符号分割的多关键字支持
                separator: ",",          //多关键字支持时的分隔符，默认为空格
                getDataMethod: "url",    //获取数据的方式，总是从 URL 获取
                effectiveFields: ["name", "code","houseNumber","apartmentName", "status"],
                effectiveFieldsAlias: {name: '房屋名称', code: "编码",houseNumber: "房号",apartmentName: "公寓", status: "状态"},
                idField: 'id',
                keyField: 'code',
                url: (yams.context.contextPath == '/' ? '' : yams.context.contextPath) + '/api/9651431c68a04d54a22f1e2e7faf827b', //优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数
                listStyle: {
                    'padding-top': 0,
                    'max-height': '425px',
                    'max-width': '800px',
                    'overflow': 'auto',
                    'border': '1px solid',
                    'width': 'auto',
                    'transition': '0.3s',
                    '-webkit-transition': '0.3s',
                    '-moz-transition': '0.3s',
                    '-o-transition': '0.3s'
                },                              //列表的样式控制
                listAlign: 'left',              //提示列表对齐位置，left/right/auto
                listHoverStyle: 'background: #07d; color:#000', //提示框列表鼠标悬浮的样式
                fnAdjustAjaxParam: function (keyword, opt) {
                    let data = {name: keyword,status:1};
                    return {
                        type: 'POST',
                        data: data,
                        dataType: 'json',
                        beforeSend: function (XMLHttpRequest) {
                            let requestHeaderParam = Dolphin.defaults.ajax.requestHeader;
                            for (let key in requestHeaderParam) {
                                XMLHttpRequest.setRequestHeader(key, requestHeaderParam[key]);
                            }
                        }
                    };
                },
                fnPreprocessKeyword: function (kw) {
                    if (kw.length < 3)
                        return false;
                    return kw;
                },
                fnProcessData: function (json) {    // url 获取数据时，对数据的处理，作为 fnGetData 的回调函数
                    let index, len, data = {value: []};
                    data.value = json.rows;
                    //字符串转化为 js 对象
                    return data;
                }
            }).on('onDataRequestSuccess', function (e, result) {
                if (result.total == 0) {
                    $("#houseId").val('');
                    $("#houseName").val('');
                }
            }).on('onSetSelectValue', function (e, keyword, data) {
                if(data.status==2){
                    alert('该房屋已出租');
                }else{
                    $("#houseId").val(data.id);
                    $("#houseName").val(data.name);
                    $("#rentalHouse").val(data.monthly);
                    $("#contractName").val(data.name);
                }
            }).on('onUnsetSelectValue', function () {
            });
        },

        /**
         * 一些页面DOM对象和事件的销毁
         */
        destroy: function () {
        }
    };
});